import 'package:just_audio/just_audio.dart';

 /*
 * 使用单例player的好处:
 * 解决多个player同时播放导致重音问题;
 * 当widget刷新时播放中断问题;
 * 离开页面后仍继续播放问题;
 * player繁琐的层层传递问题.
 * */
class BGSinglePlayer {
  late AudioPlayer audioPlayer;

  static final BGSinglePlayer _instance = BGSinglePlayer._internal();
  int _playState = 0;
  String _oldUrl = '';

  factory BGSinglePlayer() {
    return _instance;
  }

  BGSinglePlayer._internal() {
    audioPlayer = AudioPlayer();

    audioPlayer.playerStateStream.listen((playerState) {
      final processingState = playerState.processingState;
      if (processingState == ProcessingState.loading ||
          processingState == ProcessingState.buffering) {
      } else if (!playerState.playing) {
        _playState = 0;
      } else if (processingState != ProcessingState.completed) {
        _playState = 1;
      } else {
        _oldUrl = '';
        audioPlayer.stop();
      }
    });
  }

  Future play(String? url) async {
    if(url != null && url != ''){
      if(url == _oldUrl){
        _playState == 0?audioPlayer.play():audioPlayer.pause();
      }else{
        audioPlayer.setUrl(url);
        _oldUrl = url;
        audioPlayer.play();
      }
    }
  }

  Future playDirect(String? url) async {
    if(url != null && url != ''){
      audioPlayer.setUrl(url);
      audioPlayer.play();
    }
  }

  Future playByAsset(String url) async {
    audioPlayer.setAsset(url);
    audioPlayer.play();
  }

  Future stop() async {
    audioPlayer.stop();
  }
}
